/*
 * ====================================================================
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 *
 */
package com.vidmt.api.modules.sys.pay.wx;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.KeyStore;

import javax.net.ssl.SSLContext;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;

import com.vidmt.api.modules.sys.utils.VUtil;

/**
 * This example demonstrates how to create secure connections with a custom SSL
 * context.
 */
public class WxCerHttps {
	private static final Logger log = LoggerFactory.getLogger(WxCerHttps.class);
	private static CloseableHttpClient client;

	private static CloseableHttpClient getHttpClient() {
		if (null == client) {
			try {
				KeyStore keyStore = KeyStore.getInstance("PKCS12");
				Resource resource = VUtil.loadClasspathResource("certificates/wx/apiclient_cert.p12");
				InputStream is = resource.getInputStream();
				try {
					keyStore.load(is, WxPayConfig.WXPAY_MERCHANT_ID.toCharArray());
				} finally {
					is.close();
				}
				// Trust own CA and all self-signed certs
				SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, "10016225".toCharArray())
						.build();
				// Allow TLSv1 protocol only
				javax.net.ssl.HostnameVerifier hv = SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER;
				SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" },
						null, hv);
				client = HttpClients.custom().setSSLSocketFactory(sslsf).build();
			} catch (Exception e) {
				log.error("WX HTTPS CER error, httpclient is null", e);
			}

		}
		return client;
	}

	public static String postStr(String url, String xml) throws Exception {
		HttpPost httpPost = new HttpPost("https://api.mch.weixin.qq.com/secapi/pay/refund");
		httpPost.setEntity(new StringEntity(xml, "UTF-8"));
		httpPost.setHeader("Accept", "application/json");
		httpPost.setHeader("Content-type", "application/json");
		return httpStr(httpPost);
	}

	private static String httpStr(HttpUriRequest req) throws Exception {

		// HttpGet httpget = new
		// HttpGet("https://api.mch.weixin.qq.com/secapi/pay/refund");
		CloseableHttpResponse response = getHttpClient().execute(req);
		try {
			HttpEntity entity = response.getEntity();

			System.out.println("----------------------------------------");
			System.out.println(response.getStatusLine());
			if (entity != null) {
				System.out.println("Response content length: " + entity.getContentLength());
				BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent()));
				String tmp;
				StringBuilder sb = new StringBuilder();
				while ((tmp = bufferedReader.readLine()) != null) {
					sb.append(tmp);
				}
				return sb.toString();
			}
			EntityUtils.consume(entity);
			return null;
		} finally {
			response.close();
		}
	}
}
